import Vue from 'vue'
import VueRouter from 'vue-router'

import asyncRoutes from './asyncRoutes'

Vue.use(VueRouter)

/*
 * If not building with SSR mode, you can
 * directly export the Router instantiation;
 *
 * The function below can be async too; either use
 * async/await or return a Promise which resolves
 * with the Router instance.
 */


export default function (/* { store, ssrContext } */) {
  const Router = new VueRouter({
    scrollBehavior: () => ({ x: 0, y: 0 }),
    routes: [
      {
        path: '/',
        name: 'Home',
        component: () => import('layouts/MainLayout.vue'),
        meta: {
          title: '首页',
          icon: 'mdi-home',
          role: [],
        },
        // redirect: { name: 'Dashboard' },
        redirect: { name: 'Login' },
        // children: routes
        children: asyncRoutes
        // children: []
      },
      {
        path: '/Login',
        name: 'Login',
        component: () => import('pages/Login.vue'),
        meta: {
          title: '登录',
          icon: '',
          role: []
        }
      },
      {
        path: '*',
        // 和下面导航守卫里相呼应
        name: 'Error404',
        component: () => import('pages/Error404.vue')
      }

    ],
    // Leave these as they are and change in quasar.conf.js instead!
    // quasar.conf.js -> build -> vueRouterMode
    // quasar.conf.js -> build -> publicPath
    mode: process.env.VUE_ROUTER_MODE,
    base: process.env.VUE_ROUTER_BASE
  })

  Router.beforeEach((to, from, next) => {
    if (to.path === '/Login') {
      next()
    } else {
      let _token = localStorage.getItem('Authorization')
      if (_token === null || _token === '') {
        next('/Login')
      } else {
        // 获取权限列表，防止进入非权限页面
        let _roles = localStorage.getItem('Roles')
        if (_roles === '') {
          next('/Login')
        } else if (_roles === 'all') {
          next()
        } else {
          _roles = _roles.split(',')
          // roles名单添加404页面name，避免死循环
          _roles.push('Error404')
          if (_roles.indexOf(to.name) > -1) {
            next();
          } else {
            Router.push('Error404');
          }
        }
        // next()
      }
    }
  });


  return Router
}
